/*
 * COPYRIGHT. ShenZhen JiMi Technology Co., Ltd. 2017.
 * ALL RIGHTS RESERVED.
 *
 * No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
 * on any form or by any means, electronic, mechanical, photocopying, recording, 
 * or otherwise, without the prior written permission of ShenZhen JiMi Network Technology Co., Ltd.
 *
 * Amendment History:
 * 
 * Date                   By              Description
 * -------------------    -----------     -------------------------------------------
 * 2017年4月12日    li.shangzhi         Create the class
 * http://www.jimilab.com/
 */

package com.jimi.api.user.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.oval.constraint.Length;
import net.sf.oval.constraint.MemberOf;
import net.sf.oval.constraint.NotBlank;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.jimi.api.user.UserApi;
import com.jimi.api.user.vo.CoreUserVo;
import com.jimi.api.user.vo.DeviceInfoVo;
import com.jimi.api.user.vo.DeviceLocationInfoVo;
import com.jimi.exception.ApiErrorCode;
import com.jimi.exception.ErrorCode;
import com.jimi.framework.base.BaseController;
import com.jimi.framework.bean.BeanUtil;
import com.jimi.framework.interceptor.loginsecurity.LoginSecurity;
import com.jimi.framework.utils.DESEncrypt;
import com.jimi.framework.utils.ResultModel;
import com.jimi.utils.MessageSourceUtil;
import com.jimi.web.api.IUserApiService;
import com.jimi.web.dto.input.UserInfoInputDto;
import com.jimi.web.dto.output.CoreUserOutputDto;
import com.jimi.web.dto.output.DeviceInfoOutputDto;
import com.jimi.web.dto.output.DeviceLocationInfoOutputDto;

/**
 * @FileName UserApiController.java
 * @Description:
 *
 * @Date 2017年4月12日 下午1:48:48
 * @author li.shangzhi
 * @version 1.0
 */
@RestController
@RequestMapping(value = "/user")
public class UserApiController extends BaseController implements UserApi {

	@Autowired
	private IUserApiService userApiService;

	@ResponseBody
	@LoginSecurity
	@RequestMapping(value = "/getAccounts", params = { "method=jimi.user.child.list" }, produces = { "application/json" }, method = {
			RequestMethod.GET, RequestMethod.POST })
	@Override
	public ResponseEntity<ResultModel> getAccounts(
//			@NotBlank(message = "api.method.invalid") @Length(min = 10, max = 20, message = "api.method.invalid") @RequestParam(value = "method", required = true) String method,
			@NotBlank(message = "api.appkey.invalid") @Length(min = 10, max = 32, message = "api.appkey.invalid") @RequestParam(value = "app_key", required = true) String appKey,
//			@NotBlank(message = "api.timestamp.invalid") @DateRange(format = "yyyy-MM-dd HH:mm:ss", message = "api.timestamp.invalid") @RequestParam(value = "timestamp", required = true) String timestamp,
//			@NotBlank(message = "api.format.invalid") @MemberOf(value = { "json", "xml" }, message = "api.format.invalid") @RequestParam(value = "format", required = true) String format,
//			@NotBlank(message = "api.version.invalid") @MemberOf(value = { "1.0" }, message = "api.version.invalid") @RequestParam(value = "v", required = true) String v,
//			@NotBlank(message = "api.signmethod.invalid") @MemberOf(value = { "md5" }, message = "api.signmethod.invalid") @RequestParam(value = "sign_method", required = true) String signMethod,
//			@NotBlank(message = "api.sign.invalid") @Length(min = 10, max = 32, message = "api.sign.invalid") @RequestParam(value = "sign", required = true) String sign,
			@NotBlank(message = "api.accessToken.invalid") @Length(min = 10, max = 32, message = "api.accessToken.invalid") @RequestParam(value = "access_token", required = true) String accessToken,
			@NotBlank(message = "api.userId.invalid") @Length(min = 3, max = 32, message = "api.userId.invalid") @RequestParam(value = "target", required = true) String target,
			HttpServletRequest request) {
		String decrypt = DESEncrypt.decrypt(appKey);
		String[] strs = decrypt.split(",");
		String projectCode = strs[0];
		String userId = strs[1];
		CoreUserOutputDto coreUserOutputDto = userApiService.checkUserRange(userId, target);
		if (null == coreUserOutputDto) {
			return new ResponseEntity<ResultModel>(new ResultModel(ErrorCode.INVALID_USER_ERROR), HttpStatus.OK);
		}
		List<CoreUserOutputDto> outputDtoList = userApiService.getAccounts(String.valueOf(coreUserOutputDto.getId()));
		List<CoreUserVo> coreUserVoList = (List<CoreUserVo>) BeanUtil.convertBeanList(outputDtoList, CoreUserVo.class);
		ResultModel result = new ResultModel();
		result.setResult(coreUserVoList);
		return new ResponseEntity<ResultModel>(result, HttpStatus.OK);
	}

	@ResponseBody
	@LoginSecurity
	@RequestMapping(value = "/getDevices", params = { "method=jimi.user.device.list" }, produces = { "application/json" }, method = {
			RequestMethod.GET, RequestMethod.POST })
	@Override
	public ResponseEntity<ResultModel> getDevices(
//			@NotBlank(message = "api.method.invalid") @Length(min = 10, max = 20, message = "api.method.invalid") @RequestParam(value = "method", required = true) String method,
			@NotBlank(message = "api.appkey.invalid") @Length(min = 10, max = 32, message = "api.appkey.invalid") @RequestParam(value = "app_key", required = true) String appKey,
//			@NotBlank(message = "api.timestamp.invalid") @DateRange(format = "yyyy-MM-dd HH:mm:ss", message = "api.timestamp.invalid") @RequestParam(value = "timestamp", required = true) String timestamp,
//			@NotBlank(message = "api.format.invalid") @MemberOf(value = { "json", "xml" }, message = "api.format.invalid") @RequestParam(value = "format", required = true) String format,
//			@NotBlank(message = "api.version.invalid") @MemberOf(value = { "1.0" }, message = "api.version.invalid") @RequestParam(value = "v", required = true) String v,
//			@NotBlank(message = "api.signmethod.invalid") @MemberOf(value = { "md5" }, message = "api.signmethod.invalid") @RequestParam(value = "sign_method", required = true) String signMethod,
//			@NotBlank(message = "api.sign.invalid") @Length(min = 10, max = 32, message = "api.sign.invalid") @RequestParam(value = "sign", required = true) String sign,
			@NotBlank(message = "api.accessToken.invalid") @Length(min = 10, max = 32, message = "api.accessToken.invalid") @RequestParam(value = "access_token", required = true) String accessToken,
			@NotBlank(message = "api.userId.invalid") @Length(min = 3, max = 32, message = "api.userId.invalid") @RequestParam(value = "target", required = true) String target,
			HttpServletRequest request) {
		String decrypt = DESEncrypt.decrypt(appKey);
		String[] strs = decrypt.split(",");
		String projectCode = strs[0];
		String userId = strs[1];
		CoreUserOutputDto coreUserOutputDto = userApiService.checkUserRange(userId, target);
		if (null == coreUserOutputDto) {
			return new ResponseEntity<ResultModel>(new ResultModel(ErrorCode.INVALID_USER_ERROR), HttpStatus.OK);
		}
		List<DeviceInfoOutputDto> outputDtoList = userApiService.getDevices(String.valueOf(coreUserOutputDto.getId()));
		List<DeviceInfoVo> deviceInfoVoList = (List<DeviceInfoVo>) BeanUtil.convertBeanList(outputDtoList, DeviceInfoVo.class);
		ResultModel result = new ResultModel();
		result.setResult(deviceInfoVoList);
		return new ResponseEntity<ResultModel>(result, HttpStatus.OK);
	}

	@ResponseBody
	@LoginSecurity
	@RequestMapping(value = "/getAllLocations", params = { "method=jimi.user.device.location.list" }, produces = { "application/json" }, method = {
			RequestMethod.GET, RequestMethod.POST })
	@Override
	public ResponseEntity<ResultModel> getAllLocations(
//			@NotBlank(message = "api.method.invalid") @Length(min = 10, max = 20, message = "api.method.invalid") @RequestParam(value = "method", required = true) String method,
			@NotBlank(message = "api.appkey.invalid") @Length(min = 10, max = 32, message = "api.appkey.invalid") @RequestParam(value = "app_key", required = true) String appKey,
//			@NotBlank(message = "api.timestamp.invalid") @DateRange(format = "yyyy-MM-dd HH:mm:ss", message = "api.timestamp.invalid") @RequestParam(value = "timestamp", required = true) String timestamp,
//			@NotBlank(message = "api.format.invalid") @MemberOf(value = { "json", "xml" }, message = "api.format.invalid") @RequestParam(value = "format", required = true) String format,
//			@NotBlank(message = "api.version.invalid") @MemberOf(value = { "1.0" }, message = "api.version.invalid") @RequestParam(value = "v", required = true) String v,
//			@NotBlank(message = "api.signmethod.invalid") @MemberOf(value = { "md5" }, message = "api.signmethod.invalid") @RequestParam(value = "sign_method", required = true) String signMethod,
//			@NotBlank(message = "api.sign.invalid") @Length(min = 10, max = 32, message = "api.sign.invalid") @RequestParam(value = "sign", required = true) String sign,
			@NotBlank(message = "api.accessToken.invalid") @Length(min = 10, max = 32, message = "api.accessToken.invalid") @RequestParam(value = "access_token", required = true) String accessToken,
			@NotBlank(message = "api.userId.invalid") @Length(min = 3, max = 32, message = "api.userId.invalid") @RequestParam(value = "target", required = true) String target,
			@RequestParam(value = "map_type", defaultValue = "", required = false) String mapType, HttpServletRequest request) {
		if (StringUtils.isNotBlank(mapType) && (!"BAIDU".equals(mapType) && !"GOOGLE".equals(mapType))) {
			return new ResponseEntity<ResultModel>(new ResultModel(ApiErrorCode.PARAM_MAPTYPE_ERROR), HttpStatus.OK);
		}
		String decrypt = DESEncrypt.decrypt(appKey);
		String[] strs = decrypt.split(",");
		String projectCode = strs[0];
		String userId = strs[1];
		CoreUserOutputDto coreUserOutputDto = userApiService.checkUserRange(userId, target);
		if (null == coreUserOutputDto) {
			return new ResponseEntity<ResultModel>(new ResultModel(ErrorCode.INVALID_USER_ERROR), HttpStatus.OK);
		}
		List<DeviceLocationInfoOutputDto> outputDtoList = userApiService
				.getAllLocations(String.valueOf(coreUserOutputDto.getId()), mapType);
		List<DeviceLocationInfoVo> resultList = (List<DeviceLocationInfoVo>) BeanUtil.convertBeanList(outputDtoList,
				DeviceLocationInfoVo.class);
		ResultModel result = new ResultModel();
		result.setResult(resultList);
		return new ResponseEntity<ResultModel>(result, HttpStatus.OK);
	}

	@ResponseBody
	@LoginSecurity
	@RequestMapping(value = "/createUsers", params = { "method=jimi.user.child.create" }, produces = { "application/json" }, method = { RequestMethod.POST })
	@Override
	public ResponseEntity<ResultModel> createUsers(
//			@NotBlank(message = "api.method.invalid") @Length(min = 10, max = 20, message = "api.method.invalid") @RequestParam(value = "method", required = true) String method,
			@NotBlank(message = "api.appkey.invalid") @Length(min = 10, max = 32, message = "api.appkey.invalid") @RequestParam(value = "app_key", required = true) String appKey,
//			@NotBlank(message = "api.timestamp.invalid") @DateRange(format = "yyyy-MM-dd HH:mm:ss", message = "api.timestamp.invalid") @RequestParam(value = "timestamp", required = true) String timestamp,
//			@NotBlank(message = "api.format.invalid") @MemberOf(value = { "json", "xml" }, message = "api.format.invalid") @RequestParam(value = "format", required = true) String format,
//			@NotBlank(message = "api.version.invalid") @MemberOf(value = { "1.0" }, message = "api.version.invalid") @RequestParam(value = "v", required = true) String v,
//			@NotBlank(message = "api.signmethod.invalid") @MemberOf(value = { "md5" }, message = "api.signmethod.invalid") @RequestParam(value = "sign_method", required = true) String signMethod,
//			@NotBlank(message = "api.sign.invalid") @Length(min = 10, max = 32, message = "api.sign.invalid") @RequestParam(value = "sign", required = true) String sign,
			@NotBlank(message = "api.accessToken.invalid") @Length(min = 10, max = 32, message = "api.accessToken.invalid") @RequestParam(value = "access_token", required = true) String accessToken,
			@NotBlank(message = "api.topAccount.invalid") @Length(min = 3, max = 30, message = "api.topAccount.invalid") @RequestParam(value = "top_account", required = true) String topAccount,
			@NotBlank(message = "api.nickName.invalid") @Length(min = 3, max = 50, message = "api.nickName.invalid") @RequestParam(value = "nick_name", required = true) String nickName,
			@NotBlank(message = "api.accountType.invalid") @MemberOf(value = { "8", "9", "11" }, message = "api.version.invalid") @RequestParam(value = "account_type", required = true) String accountType,
			@NotBlank(message = "api.account.invalid") @Length(min = 3, max = 30, message = "api.account.invalid") @RequestParam(value = "account", required = true) String account,
			@NotBlank(message = "api.password.invalid") @Length(min = 32, max = 32, message = "api.password.invalid") @RequestParam(value = "password", required = true) String password,
			@Length(min = 0, max = 20, message = "api.phone.invalid") @RequestParam(value = "phone", defaultValue = "", required = false) String phone,
			@Length(min = 0, max = 50, message = "api.email.invalid") @RequestParam(value = "email", defaultValue = "", required = false) String email,
			@Length(min = 0, max = 50, message = "api.contact.invalid") @RequestParam(value = "contact", defaultValue = "", required = false) String contact,
			@Length(min = 0, max = 50, message = "api.companyName.invalid") @RequestParam(value = "company_name", defaultValue = "", required = false) String companyName,
			HttpServletRequest request) {
		String decrypt = DESEncrypt.decrypt(appKey);
		String[] strs = decrypt.split(",");
		String projectCode = strs[0];
		String userId = strs[1];
		CoreUserOutputDto coreUserOutputDto = userApiService.checkUserRange(userId, topAccount);
		if (null == coreUserOutputDto) {
			return new ResponseEntity<ResultModel>(new ResultModel(ErrorCode.INVALID_USER_ERROR), HttpStatus.OK);
		}
		UserInfoInputDto userInfoInputDto = new UserInfoInputDto();
		userInfoInputDto.setUserId(String.valueOf(coreUserOutputDto.getId()));
		userInfoInputDto.setTopAccount(topAccount);
		userInfoInputDto.setNickName(nickName);
		userInfoInputDto.setAccountType(accountType);
		userInfoInputDto.setAccount(account);
		userInfoInputDto.setPassword(password);
		userInfoInputDto.setPhone(phone);
		userInfoInputDto.setEmail(email);
		userInfoInputDto.setContact(contact);
		userInfoInputDto.setCompanyName(companyName);
		String code = userApiService.saveUser(userInfoInputDto);
		ResultModel resultModel = new ResultModel();
		if ("0".equals(code)) {
			resultModel.setCode(0);
			resultModel.setMessage(MessageSourceUtil.getMessage("api.user.create.ok"));
		} else {
			resultModel.setCode(12001); // 添加用户操作失败
			resultModel.setMessage(MessageSourceUtil.getMessage("api.user.create.fail", code));
		}
		return new ResponseEntity<ResultModel>(resultModel, HttpStatus.OK);
	}

}
